package com.cnxjs.shs4et.service.impl;

import com.cnxjs.shs4et.common.Result;
import com.cnxjs.shs4et.entity.Topic;
import com.cnxjs.shs4et.repository.TopicRepository;
import com.cnxjs.shs4et.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TopicImpl implements TopicService {

    @Autowired
    private TopicRepository topicRepository;

    // 分页查询所有帖子
    @Override
    public Result findAll(Pageable pageable) {
        return Result.success(topicRepository.findAllByIsLocked(pageable, 0));
    }

    // 按照具体板块分页查所有帖子
    @Override
    public Result findByBlock(Pageable pageable, Integer forumId) {
        return Result.success(topicRepository.findAllByForum(pageable, forumId));
    }

    // 按照论坛分页查所有帖子
    @Override
    public Result findByForum(Integer page, Integer size, String sortRule, String name) {
        Integer offset = page * size;
        return Result.success(topicRepository.findAllByForumName(offset, size, sortRule, name, page));
    }

    // 发帖子
    @Override
    public Result add(Topic topic) {
        return Result.success(topicRepository.save(topic));
    }

    @Override
    public Result update(Topic topic) {
        Topic topicInDB = topicRepository.findById(topic.getId());
        if (topicInDB != null) {
            topicInDB.setTitle(topic.getTitle());
            topicInDB.setContent(topic.getContent());
            topicInDB.setForum(topic.getForum());
            topicRepository.save(topicInDB);
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Result delete(Integer id) {
        Topic topic = topicRepository.findById(id);
        topic.setIsLocked(1);
        topicRepository.save(topic);
        return Result.success("删除成功");
    }

    @Override
    public Result findByTitle(Pageable pageable, String title) {
        List<Topic> topic = topicRepository.findAllByTitleLike(pageable, title);
        if (topic != null)
            return Result.success(topic);
        else
            return Result.error("没有找到帖子");
    }

    @Override
    public void addLike(Integer id) {
        Topic topic = topicRepository.findById(id);
        topic.setRecommendCount(topic.getRecommendCount() + 1);
        topicRepository.save(topic);
    }
}
